﻿using Ledict.ConditionExtract.Base;
using Ledict.ConditionExtract.BLL;
using Ledict.ConditionExtract.BLL.WorkProcess;
using Ledict.ConditionExtract.Common;
using Ledict.ConditionExtract.Model;
using Ledict.Utility.Helper;
using Ledict.Utility.Msg;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Ledict.Utility.Frm;

namespace Ledict.ConditionExtract.Frm.DataProcess
{
    /// <summary>
    /// 刑事数据处理窗体（各业务考虑后期各自的特殊性，独立开） todo by zhangpeng 2016-12-14
    /// </summary>
    public partial class CrimeDataProcess1 : BaseForm
    {
        #region 界面初始化

        //静态锁
        private static readonly object Lock = new object();

        static CrimeDataProcess1 _default;
        public static CrimeDataProcess1 Default
        {
            get
            {
                if (_default == null || _default.IsDisposed)
                {
                    lock (Lock)
                    {
                        if (_default == null || _default.IsDisposed)
                        {
                            _default = new CrimeDataProcess1();
                        }
                    }

                }
                return _default;
            }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public CrimeDataProcess1()
        {
            InitializeComponent();
            //t_Case_HeadWords.TreeView.AfterExpand += new TreeViewEventHandler(t_Case_HeadWords_AfterExpand);
            //t_Global_Court.TreeView.AfterExpand += new TreeViewEventHandler(t_Global_Court_AfterExpand);
            //NowProcessNode.TreeView.AfterExpand += new TreeViewEventHandler(NowProcessNode_AfterExpand);
        }

        #endregion

        TreeDataBLL trbll = new TreeDataBLL();
        CaseCauseBLL casecausebLL = new CaseCauseBLL();
        Express_WordBLL wordbll = new Express_WordBLL();
        Express_AddElement addelementbll = new Express_AddElement();
        NewIDBLL newid = new NewIDBLL();
        //AboutRegexBLL regexbll = new AboutRegexBLL();
        //Ledict.Regex.BLL.Reg_RegexsBLL addreg = new Ledict.Regex.BLL.Reg_RegexsBLL();
        ExpressGroupSituationBLL expresitu = new ExpressGroupSituationBLL();
        //Express_MatchSituationBLL match = new Express_MatchSituationBLL();
        //Express_SourceBLL SourceBLL = new Express_SourceBLL();

        //AboutRegexBLL aboutreg = new AboutRegexBLL();
        RegexParse.RegexParse getregex = new RegexParse.RegexParse();

        //ProcessDataSourceBLL datas = new ProcessDataSourceBLL();
        WorkThread_Public work = new WorkThread_Public();
        //ElementAnalyze ea = new ElementAnalyze();
        WordBankKeyWordsBLL wordbankkeywordsbll = new WordBankKeyWordsBLL();
        //Reg_InfoRegexRelationBLL unitrelation = new Reg_InfoRegexRelationBLL();
        Express_WordBankRelBLL express_wordbankrelbll = new Express_WordBankRelBLL();
        WordBankBLL wordbankbll = new WordBankBLL();
        DataProcess_EditNode dataprocess_editnode = new DataProcess_EditNode();
        Express_MatchSituationBLL express_matchsituationbll = new Express_MatchSituationBLL();
        SYS_CaseCause caseModel;
        Thread workThread1;


        #region 共有变量

        private string sort = "";
        private string IsASC = "";
        private string SelectText = "";
        private string SelectWBK_ID = "";
        private TreeNode clicknode = null;
        //private string IsAddData = "";

        private string TypeName = "刑事罪名";
        string EW_IDText = "";
        int GridViewRowNumber = 0;

        int IsContentOrAddElement = 1;//1为编辑文本0 为编辑要素
        private string FirId = "1000";
        private List<TreeNode> NodeList = new List<TreeNode>();

        public DataTable m_single = new DataTable();
        public DataTable m_group = new DataTable();
        public DataTable m_matchsituation = new DataTable();
        public DataTable m_causecode = new DataTable();
        Express_MatchSituationBLL MatchSituationbll = new Express_MatchSituationBLL();
        string groupStr = string.Empty;
        string singleStr = string.Empty;
        #endregion

        private void DataProcess_Load(object sender, EventArgs e)//初始化树
        {
            //表述内容布局
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            //添加要素布局
            DV_AddElement.AutoGenerateColumns = false;
            DV_AddElement.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            //GetData("t_Case_HeadWords");
            //GetData("t_Case_JudicialProcedure");
            //GetData("t_Case_Property");
            //GetData("t_Case_ParagraphType");

            //GetData("t_Global_Court");

            //CaseCauseTree();
            // CaseCauseTree_Process();


            //TypeName = "刑事罪名";
            //GetColor();
            //Button sendButton = (Button)sender;
            //sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();

            //表述关系表
            m_matchsituation.Columns.Add("MS_ID");
            m_matchsituation.Columns.Add("CauseGroupID");
            m_matchsituation.Columns.Add("SituationID");
            m_matchsituation.Columns.Add("SituationType");
            m_matchsituation.Columns.Add("SituationName");
            m_matchsituation.Columns.Add("IsMatch");
            m_matchsituation.Columns.Add("MatchSource");
            m_matchsituation.Columns.Add("AffirmIdeaSource");
            m_matchsituation.Columns.Add("AffirmIdeaResult");
            m_matchsituation.Columns.Add("notAffirmReson");
            m_matchsituation.Columns.Add("ParentID");
            m_matchsituation.Columns.Add("AllSituationIDs");
            m_matchsituation.Columns.Add("AllParentID");
            m_matchsituation.Columns.Add("CC_IsShowExpress");
            m_matchsituation.Columns.Add("UpdateTime");          
            m_matchsituation.Columns.Add("CC_GlobalOrder");

        }

        #region 左侧树

        public void CaseCauseTree()
        {
            #region 初始化
            this.tVCaseCause.Nodes.Clear();
            NodeList = new List<TreeNode>();

            StacticQuery.Text = "";
            CurrNodeNum.Text = "";
            SumQuery.Text = "";
            #endregion

            DataTable dt = trbll.GetCauseTree_Two("", 0);// 第一层

            if (dt.Rows.Count > 0)
            {
                DataRow[] arrayDR = dt.Select("name='" + TypeName + "'");

                foreach (DataRow caseTreeNodeRode in arrayDR)
                {
                    TreeNode node = new TreeNode();

                    node.Text = LdFormat.ObjectToString(caseTreeNodeRode["name"]);
                    node.Tag = caseTreeNodeRode["id"];
                    node.Name = LdFormat.ObjectToString(caseTreeNodeRode["CC_NodeType"].ToString() + "," + caseTreeNodeRode["TableName"].ToString());
                    FirId = caseTreeNodeRode[0].ToString();
                    if (trbll.GetCauseTree_Two(node.Tag.ToString(), 0).Rows.Count > 0)//第二层
                    {
                        node.Nodes.Add(new TreeNode());
                    }
                    tVCaseCause.Nodes.Add(node);
                    NodeList.Add(node);
                }
            }
        }
        /// <summary>
        /// 显示下一级树节点
        /// </summary>
        /// <param name="parentNode"></param>
        private void CaseCauseTreeChild(TreeNode parentNode)
        {
            DataTable caseTreeNodeRode = GetChild(parentNode);
            if (caseTreeNodeRode.Rows.Count == 0)
                return;
            for (int i = 0; i < caseTreeNodeRode.Rows.Count; i++)//下级
            {

                TreeNode node = new TreeNode();

                node.Text = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["name"]);
                node.Tag = caseTreeNodeRode.Rows[i]["id"];
                node.Name = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["CC_NodeType"].ToString() + "," + caseTreeNodeRode.Rows[i]["TableName"].ToString());

                if (node.Text == "组合" || GetChild(node).Rows.Count > 0)
                {
                    node.Nodes.Add(new TreeNode());
                }

                parentNode.Nodes.Add(node);
                NodeList.Add(node);
            }
        }
        /// <summary>
        /// 获取下一级树节点
        /// </summary>
        /// <param name="parentNode">父节点</param>
        /// <returns></returns>
        private DataTable GetChild(TreeNode parentNode)
        {
            string pid = parentNode.Tag.ToString();
            string pName = parentNode.Text;

            string[] name = parentNode.Name.Split(',');
            int ptype = Convert.ToInt32(name[0]);
            int tableName = Convert.ToInt32(name[1]);
            int childType = trbll.GetChildType(pid, ptype, tableName);//下级改去哪个表查0：CaseCause 1:SYS_Express_GroupSituation
            DataTable caseTreeNodeRode;
            if (childType == 1)
            {

                if (tableName == 0) //如果是第一级 找组合单一
                {
                    int ccIsCombination = 0;
                    SYS_CaseCause model = casecausebLL.GetCaseCauseByCCID(pid);
                    if (model != null && model.CC_IsCombination == 1)
                        ccIsCombination = 1;
                    caseTreeNodeRode = trbll.GetCauseTreeTwo_ToExpressTab_Virtual(pid, ccIsCombination);

                }
                else
                {
                    if (pName == "组合") //如果是组合的，去前缀
                        pid = pid.Substring(1, pid.Length - 1);
                    caseTreeNodeRode = trbll.GetCauseTreeTwo_ToExpressTab(pid, 0);//SYS_Express_GroupSituation 
                }
            }
            else
            {
                if (pName == "单一") //如果是组合的，去前缀
                    pid = pid.Substring(1, pid.Length - 1);
                caseTreeNodeRode = trbll.GetCauseTree_Two(pid, 0); //CaseCause
            }
            return caseTreeNodeRode;

        }

        /// <summary>
        /// 展开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tVCaseCause_AfterExpand(object sender, TreeViewEventArgs e)
        {
            //if (e.Node.FirstNode.Tag == null)
            //{
                e.Node.Nodes.Clear();
                //加载下级树节点
                CaseCauseTreeChild(e.Node);
           // }
        }

        /// <summary>
        /// 选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tVCaseCause_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (clicknode != null)
                clicknode.ForeColor = Color.Black;
            clicknode = e.Node;//保存节点
            clicknode.ForeColor = Color.Red;
            //IsAddData = "";
            SelectText = "";
            SelectWBK_ID = "";
            if (clicknode.Text.Contains("（"))
            {
                panel_Attribute.Enabled = false;
            }
            else
            {
                //构成，不构成，认定，不认定显示
                panel_Attribute.Enabled = true;
            }
            //给表述内容赋值
            dataPagerMain.ChangePageNumber(1);
            //给正则列表赋值
            ShowRegText();

        }



        /// <summary>
        /// 是否有用情形
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public bool IsUseFul(TreeViewEventArgs e)
        {
            //int type = Convert.ToInt32(e.Node.Name.ToString().Split (',')[0]);
            //if (type == 4 || type == 5 || type == 6 || type == 7 || type == 8)
            //{
            return true;
            //}
            //return false;
        }
        #endregion

        #region 右侧信息列表
        /// <summary>
        /// 列表显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataPagerMain_PageNumberChanging(object sender, Controls.DataPagerPageIndexChangingEventArgs e)
        {
            if (clicknode != null)
            {
                var startRowIndex = e.StartRowIndex;
                //var maximumRows = e.MaximumRows;
                var endRowIndex = e.StartRowIndex + e.MaximumRows;
                DataTable dt;
                string id = clicknode.Tag.ToString();
                //第一种表述节点
                //第二种原SYS_CaseCause节点
                //构成，不构成
                int ismatch = IsMatch.Checked ? 1 : 0;
                //认定，不认定
                string affirmIdeaResult = IsAffirmIdeaResult.Checked ? "1" : "2";
                //
                if (id.IndexOf("EMS") >= 0)
                    id = expresitu.GetES_IDsByCCId(id, ismatch, affirmIdeaResult);
                //else
                //id
                //去表述表中取数据
                dt = wordbll.GetExractContent(id, sort, IsASC, SelectText, SelectWBK_ID, 0);

                //给表述DataGridView数据源赋值
                if (dt.Rows.Count > 0)
                {
                    e.TotalCount = dt.Rows.Count;
                    DataTable newdt = new DataTable();
                    newdt = dt.Clone();
                    DataRow[] dr = dt.Select("showindex>" + startRowIndex + " and showindex<=" + endRowIndex);
                    for (int i = 0; i < dr.Length; i++)
                    {
                        newdt.ImportRow((DataRow)dr[i]);
                    }
                    dataGridView1.DataSource = newdt;
                }
                else
                {
                    dataGridView1.DataSource = new DataTable();
                }
            }

        }
        /// <summary>
        /// 转到添加要素界面
        /// </summary>
        private void ToAddWordBanks()
        {
            tabControl1.SelectTab("tabPage2");
            if (null != clicknode)
            {
                linkAddWB.Text = string.Format("<<{0}", clicknode.Text);
            }
            GetWordkeyByCCId();
        }

        /// <summary>
        /// 转到添加要素界面
        /// </summary>
        private void ShowRegText()
        {
            DataTable dt = new DataTable();
            //dt.Columns.Add("ER_Name");
            //dt.Columns.Add("ER_OperateType");
            //dt.Columns.Add("ER_RegexText");
            //string id = clicknode.Tag.ToString();
            //id = expresitu.GetES_SituationIdsById(id);
            //string regCode = casecausebLL.GetRegCodeByJudgeBook(id);
            //IList<Ledict.Regex.Model.Reg_Regex> reglist = getregex.GetRegexs(regCode);
            //foreach (Ledict.Regex.Model.Reg_Regex item in reglist)
            //{
            //    DataRow dr = dt.NewRow();
            //    dr[0] = item.ER_Name;
            //    switch (item.ER_OperateType)
            //    {
            //        case 1:
            //            dr[1] = "提取";
            //            break;
            //        case 2:
            //            dr[1] = "替换";
            //            break;
            //        case 3:
            //            dr[1] = "匹配";
            //            break;

            //    }
            //    dr[2] = item.ER_RegexText;
            //    dt.Rows.Add(dr);
            //}
            //获取正则列表数据源
            GV_Reg.DataSource = dt;
        }


        /// <summary>
        /// 转到节点树界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            tabControl1.SelectTab("tabPage1");

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DV_AddElement_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 2)  //添加节点重跑数据
            {
                try
                {
                    OpenNodeTree();
                }
                catch (Exception error)
                {

                    MsgBox.Err("添加要素失败!");
                    Log.ErrorLog(error.Message);

                }
            }
            else if (e.ColumnIndex == 0)
            {
                // SelectText  = WhereLike.ToWherelike(DV_AddElement.Rows[e.RowIndex].Cells["Element"].Value.ToString().Replace("\r\n", ""), "EW_Content", 1);  
                SelectWBK_ID = DV_AddElement.Rows[e.RowIndex].Cells["WBK_ID"].Value.ToString();
                SelectText = "";

                dataPagerMain.ChangePageNumber(1);

            }

        }
        private void GetWordkeyByCCId()
        {
            if (clicknode != null)
            {
                string id = clicknode.Tag.ToString();

                //第一种表述节点
                //第二种原SYS_CaseCause节点
                int ismatch = IsMatch.Checked ? 1 : 0;
                string affirmIdeaResult = IsAffirmIdeaResult.Checked ? "1" : "2";
                id = expresitu.GetES_IDsByCCId(id, ismatch, affirmIdeaResult);
                DataTable wordBankKeysdt = wordbll.GetAllwordBankKeys(id);
                DV_AddElement.DataSource = wordBankKeysdt;
            }
        }


        /// <summary>
        /// 编辑列表（单击）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                #region 对勾和差
                if (e.ColumnIndex == 7 || e.ColumnIndex == 8)
                {
                    DataGridViewCheckBoxCell checkCellRight = (DataGridViewCheckBoxCell)dataGridView1.Rows[e.RowIndex].Cells["Right"];
                    DataGridViewCheckBoxCell checkCellwrong = (DataGridViewCheckBoxCell)dataGridView1.Rows[e.RowIndex].Cells["wrong"];
                    if (e.ColumnIndex == 7)
                    {
                        if (Convert.ToBoolean(checkCellRight.Value) == true)
                        {
                            checkCellRight.Value = false;
                            checkCellwrong.Value = true;
                        }
                        else
                        {
                            checkCellRight.Value = true;
                            checkCellwrong.Value = false;
                        }

                    }
                    if (e.ColumnIndex == 8)
                    {
                        if (Convert.ToBoolean(checkCellwrong.Value) == true)
                        {
                            checkCellRight.Value = true;
                            checkCellwrong.Value = false;
                        }
                        else
                        {
                            checkCellRight.Value = false;
                            checkCellwrong.Value = true;
                        }
                    }

                    SYS_Express_Word model = new SYS_Express_Word();
                    model.EW_Right = Convert.ToInt32(checkCellRight.Value);
                    model.EW_Wrong = Convert.ToInt32(checkCellwrong.Value);
                    model.EW_ID = dataGridView1.Rows[e.RowIndex].Cells["EW_ID"].Value.ToString();

                    wordbll.UpdateChooseState_Process(model);
                    if (model.EW_Right == 1)//添加到表述库加工
                    {
                        model = wordbll.GetModel_Process(dataGridView1.Rows[e.RowIndex].Cells["EW_ID"].Value.ToString());

                        UpdateCC_IsShowExpress(clicknode);

                        if (!wordbll.Exists_Word(model))
                        {
                            wordbll.Add_Word(model);//添加word 表
                        }
                    }
                }

                #endregion
                if (e.ColumnIndex == 2)  //编辑文本
                {

                    EW_IDText = dataGridView1.Rows[e.RowIndex].Cells["EW_ID"].Value.ToString();

                    textBox1.Text = "";
                    textBox1.Text = dataGridView1.Rows[e.RowIndex].Cells["EW_Content"].Value.ToString();
                    //byte[] buffer = Encoding.UTF8.GetBytes(dataGridView1.Rows[e.RowIndex].Cells["EW_Content"].Value.ToString());
                    //textBox1.Text = Encoding.GetEncoding("UTF-8").GetString(buffer);
                    GridViewRowNumber = e.RowIndex;
                    ColorWord();

                }

            }

        }

        /// <summary>
        /// 自己和所有父级节点记状态
        /// </summary>
        /// <param name="nowNode"></param>
        private void UpdateCC_IsShowExpress(TreeNode nowNode)
        {

            wordbll.UpdateCC_IsShowExpress(nowNode.Tag.ToString(), 1);
            if (nowNode.Parent != null)
                UpdateCC_IsShowExpress(nowNode.Parent);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Delete_Click(object sender, EventArgs e)
        {
            string DeleteID = "";
            int num = 0;
            for (var i = 0; i <= dataGridView1.Rows.Count - 1; i++)
            {
                var check = (DataGridViewCheckBoxCell)dataGridView1.Rows[i].Cells["Column1"];
                if (Convert.ToBoolean(check.Value))
                {
                    num++;
                }
            }
            if (num == 0)
            {
                MsgBox.Warn("请勾选需要删除的数据后再试");
                return;
            }
            if (MessageBox.Show("确认要删除数据吗？", "此删除不可恢复", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    bool res = false;
                    for (int i = 0; i <= dataGridView1.Rows.Count - 1; i++)
                    {
                        DataGridViewCheckBoxCell check = (DataGridViewCheckBoxCell)dataGridView1.Rows[i].Cells["Column1"];
                        if (Convert.ToBoolean(check.Value) == true)
                        {
                            DeleteID = dataGridView1.Rows[i].Cells["EW_ID"].Value.ToString();
                            if (DeleteID != "")
                            {

                                wordbll.Delete_WordProcess(DeleteID);
                            }

                        }
                    }
                    if (res)
                    {
                        MsgBox.OK("删除成功!");
                    }
                    else
                    {
                        MsgBox.Warn("删除失败!");
                    }
                }
                catch (Exception error)
                {
                    MsgBox.Err("删除失败!");
                    Log.ErrorLog(error.Message);

                }
                dataPagerMain.ChangePageNumber(1);
            }
        }



        /// <summary>
        /// 2017年5月15日 ljj-update 方法从未被使用
        /// 显示窗体，自动将窗体填满父窗体的工作区
        /// </summary>
        /// <param name="childForm"></param>
        //private void ShowForm(Form childForm)
        //{
        //    childForm.MdiParent = this.MdiParent;
        //    childForm.StartPosition = FormStartPosition.CenterParent;
        //    childForm.Show();
        //    childForm.Activate();
        //    childForm.Dock = DockStyle.Fill;
        //    var size = childForm.Size;
        //    var location = childForm.Location;
        //    childForm.Dock = DockStyle.None;
        //    childForm.Size = size;
        //    childForm.Location = location;
        //}
        /// <summary>
        /// 修改文本 
        /// </summary>=""
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UpdateWord_Click(object sender, EventArgs e)
        {
            if (IsContentOrAddElement == 1)
            {
                if (wordbll.UpdateContent(EW_IDText, textBox1.Text))
                {
                    MessageBox.Show("修改成功!");
                }
                else
                {
                    MessageBox.Show("修改失败!");
                }

                if (dataGridView1.Rows.Count > 0)
                {
                    DataGridViewCell checkCellwrong = (DataGridViewCell)dataGridView1.Rows[GridViewRowNumber].Cells["EW_Content"];
                    checkCellwrong.Value = textBox1.Text;
                }
            }

        }
        #endregion

        #region 多线程

        WorkThread workObj = new WorkThread();
        //工作对象
        private Thread workThread;





        //暂停(只针对第一次加工数据)
        private void Endbtn_Click(object sender, EventArgs e)
        {
            if (workThread != null)
            {
                workThread.Abort();
                workThread = null;
            }
        }

        // 显示进度条
        public void ShowProgress(int maxCount, int currentCount)
        {
            //if (this.progressBar1.InvokeRequired == false)
            //{
            //    if (currentCount < maxCount)
            //    {
            //        progressBar1.Value = currentCount;
            //        progressBar1.Maximum = maxCount;
            //        progressBar1.Text = currentCount + "/" + maxCount;
            //        label1.Text = string.Format("当前{0}条|总共{1}条", currentCount, maxCount);
            //    }
            //    else if (currentCount == maxCount)
            //    {
            //        progressBar1.Value = currentCount;
            //        progressBar1.Maximum = maxCount;
            //        progressBar1.Text = currentCount + "/" + maxCount;
            //        label1.Text = string.Format("已完成，共{0}条", maxCount);
            //        workThread = null;
            //        StaticCacheBLL.plotchildDict = new Dictionary<string, DataTable>();//清除规则缓存
            //    }
            //}
            //else
            //{
            //    ProcessShow processshow = new ProcessShow(ShowProgress);
            //    this.Invoke(processshow, new object[] { maxCount, currentCount });
            //}

        }


        /// <summary>
        /// 开始执行线程
        /// </summary>
        private void ThreadExecute(DataSourceCondition condi, string luceneSearchType)
        {
            if (!string.IsNullOrEmpty(luceneSearchType))
            {
                //  workThread = null;
                workObj.processShow = ShowProgress;
                workObj.closeForm = CloseForm;
                workObj.conditon = condi;

                workObj.LuceneSearchType = luceneSearchType.ToUpper();//设置查询lucene方法

                //workThread = new Thread(workObj.execute_Start);
                workThread = new Thread(workObj.execute_Start);
                workThread.Start();
            }
        }


        #endregion

        #region  加工条件
        /// <summary>
        /// 开始加工(组织条件)第一次加工
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// 
        //private void StartBtn_Click(object sender, EventArgs e)
        //{

        //    try
        //    {
        //        if (t_Case_HeadWords.Text.Trim() != "" && t_Case_JudicialProcedure.Text.Trim() != "" && t_Case_Property.Text.Trim() != "" && t_Case_ParagraphType.Text.Trim() != "" && NowProcessNode.Text.Trim() != "")
        //        {
        //            //先根据ID去获取该案由实体
        //            SYS_CaseCause objCaseCause = casecausebLL.GetCaseCauseByCCID(NowProcessNode.Text.Trim());
        //            if (objCaseCause != null && !string.IsNullOrEmpty(objCaseCause.CC_Name))
        //            {

        //                if (workThread == null)//创建线程
        //                {
        //                    #region 查询条件
        //                    //条件

        //                    var condi = new DataSourceCondition
        //                    {
        //                        CaseIdStart = CaseIdStart.Text.Trim(),
        //                        CaseIdEnd = CaseIdEnd.Text.Trim(),
        //                        HeadwordId = t_Case_HeadWords.Text,
        //                        JudicialProcedureId = t_Case_JudicialProcedure.Text.Trim(),
        //                        PropertyId = t_Case_Property.Text.Trim(),
        //                        ParagraphType = t_Case_ParagraphType.Text.Trim(),
        //                        Court = t_Global_Court.Text.Trim(),
        //                        SituationId = NowProcessNode.Text.Trim(),
        //                        SearchPerSize = int.Parse(ConfigHelper.AppSettings("LuceneSearchPerSize")) //每次查询个数
        //                    };

        //                    #endregion

        //                    //todo by zhangpeng:Lucene查询方法（WCF或直接通过共享方法调用）两个值：WCF，Share
        //                    var dataProcessType = ConfigHelper.AppSettings("LuceneSearchType");

        //                    if (string.IsNullOrEmpty(dataProcessType)) dataProcessType = "wcf";

        //                    //workObj = WorkThreadFactory.CreateWorkThreadObj(work.IsCriminal(condi.SituationId) ?
        //                    //       "WorkThread_first_Crime" : "WorkThread_first_People");

        //                    //执行刑事跑表述数据
        //                    workObj = WorkThreadFactory.CreateWorkThreadObj("WorkThread_first_Crime");


        //                    //开始执行
        //                    ThreadExecute(condi, dataProcessType);
        //                }
        //                else//暂停后重启
        //                {
        //                    MsgBox.Warn("当前操作未完成，请等待");
        //                    // workObj.Resume();
        //                }

        //            }
        //            else
        //            {
        //                MsgBox.Warn("不存在该案由节点，请重新填写!");
        //            }
        //        }
        //        else
        //        {
        //            MsgBox.Warn(@"案由、案件性质、逻辑段、裁决程序、处理节点不可为空，请重新填写!");
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        MsgBox.Err("系统报错，请查看错误日志!");

        //        LogHelper.Error(ex.Message);
        //    }
        //}

        #region  重加工
        /// <summary>
        /// 重跑数据开始(立即处理)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Start_Again(Dictionary<string, string> AddEleDic)
        {

            //workObj = WorkThreadFactory.CreateWorkThreadObj("second");

            //NodeTree ae = NodeTree.Default;
            //if (ae.LocateNode != "")
            //{
            //    ae.Close();
            //}

            //StringBuilder elements = new StringBuilder();

            //foreach (KeyValuePair<string, string> kv in AddEleDic)//一个一个开始
            //{
            //    #region 查询条件

            //    DataSourceCondition condi = new DataSourceCondition(); //条件
            //    condi.ISAgainData = true;
            //    condi.SituationId = kv.Key;
            //    conditonList.Add(condi);
            //    #endregion

            //}
            //Threadexecute();
        }

        /// <summary>
        /// 开始处理"暂不处理"的要素（稍后处理）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExecAllStart_Click(object sender, EventArgs e)
        {
            //workObj = WorkThreadFactory.CreateWorkThreadObj("second");
            //conditonList.Clear();

            //DataTable AllElem = addelementbll.GetAllElement();

            //for (int i = 0; i < AllElem.Rows.Count; i++)
            //{

            //    #region 查询条件

            //    DataSourceCondition condi = new DataSourceCondition(); //条件
            //    condi.ISAgainData = true;
            //    condi.SituationId = AllElem.Rows[i]["StiuatonId"].ToString();
            //    conditonList.Add(condi);
            //    #endregion

            //}
            //// workObj

            //Threadexecute();

            ////清库
            //wordbll.UpdateClearElement_Process();
        }


        /// <summary>
        /// 保存"暂不处理"的要素（稍后处理）
        /// </summary>
        /// <param name="AddEleDic"></param>
        public void SaveElement(Dictionary<string, string> AddEleDic)
        {
            //ConditionExtract.NodeTree ae = ConditionExtract.NodeTree.Instance;
            //if (ae.LocateNode != "")
            //{
            //    ae.Close();
            //}

            //StringBuilder elements = new StringBuilder();
            //foreach (KeyValuePair<string, string> kv in AddEleDic)
            //{
            //    addelementbll.AddExpress_AddElement(kv.Key, kv.Value);
            //    elements.Append("," + kv.Value);
            //}

            //wordbll.UpdateAddElement_Process(EW_IDText, elements.ToString());
            //dataPagerMain.ChangePageNumber(dataPagerMain._currentPageNumber);
        }


        #endregion

        #endregion

        #region 小功能（刷新关闭 有问题）


        bool closeState = false;
        //关闭
        private void DataProcess_FormClosing(object sender, FormClosingEventArgs e)
        {

            if (workThread != null && workThread.IsAlive && e.CloseReason == CloseReason.UserClosing && !closeState)
            {
                workObj.Stop();

                e.Cancel = true;
            }

        }
        public void CloseForm()
        {
            //if (this.progressBar1.InvokeRequired == false)
            //{
            //    closeState = true;
            //    Close();
            //}
            //else
            //{
            //    CloseForm closeForm = new CloseForm(CloseForm);
            //    this.Invoke(closeForm);
            //}
        }
        //刷新
        private void button3_Click(object sender, EventArgs e)
        {
            CaseCauseTree();
        }
        #endregion

        #region 界面显示（非核心功能）

        #region 查询节点(有问题)
        DataTable Querydt;
        private void QueryNodeTxt_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                QueryNode();
            }

        }

        /// <summary>
        /// 查询
        /// </summary>
        private void QueryNode()
        {
            string queryNodeName = QueryNodeTxt.Text.Trim();

            if (queryNodeName != "")
            {
                Querydt = trbll.NodeTree_Query(FirId, queryNodeName, 2);
                StacticQuery.Text = Querydt.Rows.Count.ToString();
                if (Querydt.Rows.Count > 0)
                {
                    CurrNodeNum.Text = "1";
                    SumQuery.Text = CurrNodeNum.Text;
                    int currNode = Convert.ToInt32(CurrNodeNum.Text);
                    LinkIsVisible(currNode);
                    QueryNode_Page(Querydt, currNode);
                }
                else
                {
                    CurrNodeNum.Text = "0";
                    SumQuery.Text = CurrNodeNum.Text;
                    MessageBox.Show("没有查询到结果！");
                }
            }
            else
            {
                MessageBox.Show("请输入关键字！");
            }
        }




        private void QueryNodeBtn_Click(object sender, EventArgs e)//查询
        {
            QueryNode();
        }
        /// <summary>
        /// 下一条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Nextlinkbtn_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            CurrNodeNum.Text = (Convert.ToInt32(CurrNodeNum.Text) + 1).ToString();
            SumQuery.Text = CurrNodeNum.Text;
            int CurrNode = Convert.ToInt32(CurrNodeNum.Text);
            QueryNode_Page(Querydt, CurrNode);
            LinkIsVisible(CurrNode);


        }
        /// <summary>
        /// 上一条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Prelinkbtn_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            CurrNodeNum.Text = (Convert.ToInt32(CurrNodeNum.Text) - 1).ToString();
            SumQuery.Text = CurrNodeNum.Text;
            int CurrNode = Convert.ToInt32(CurrNodeNum.Text);
            QueryNode_Page(Querydt, CurrNode);
            LinkIsVisible(CurrNode);

        }
        /// <summary>
        /// 查询分页
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="showindex"></param>
        private void QueryNode_Page(DataTable dt, int showindex)
        {
            if (dt.Rows.Count >= showindex)
            {
                string[] NotePidArr = trbll.GetAllParentNode(dt.Rows[showindex - 1]["id"].ToString()).Split(',');
                for (int i = 0; i < NotePidArr.Length; i++)
                {

                    if (i != NotePidArr.Length - 1)
                    {
                        FindNode(NotePidArr[i]).Expand();
                    }
                    else
                    {
                        TreeNode node = FindNode(NotePidArr[i]);
                        this.tVCaseCause.SelectedNode = node;

                    }
                }
            }
            else
            {
                MessageBox.Show("跳转页码有误，重新输入！");
            }


        }
        /// <summary>
        /// 找到节点
        /// </summary>
        /// <param name="Nodeid"></param>
        /// <returns></returns>
        private TreeNode FindNode(string Nodeid)
        {
            foreach (TreeNode node in NodeList)
            {
                if (node.Tag.ToString() == Nodeid)
                {
                    return node;
                }
            }
            return null;

        }
        /// <summary>
        /// 上一条下一条是否可用
        /// </summary>
        /// <param name="CurrNode"></param>
        private void LinkIsVisible(int CurrNode)
        {
            Prelinkbtn.Enabled = true;
            Nextlinkbtn.Enabled = true;
            if (CurrNode <= 1)
            {
                Prelinkbtn.Enabled = false;
            }
            if (CurrNode >= Querydt.Rows.Count)
            {
                Nextlinkbtn.Enabled = false;
            }




        }
        /// <summary>
        /// 跳页查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GoQuery_Click(object sender, EventArgs e)
        {
            int CurrNode = Convert.ToInt32(SumQuery.Text);

            if (Querydt.Rows.Count >= CurrNode)
            {
                CurrNodeNum.Text = SumQuery.Text;
                QueryNode_Page(Querydt, CurrNode);
                LinkIsVisible(CurrNode);
            }
            else
            {
                MessageBox.Show("跳转页码有误，重新输入！");
            }

        }

        #endregion

        #region 各种树菜单(案由、类型)
        public void GetData(string Tname)
        {
            //DataTable dt = trbll.GetTreeHeadWords("", Tname);// 第一层
            //DataRow[] arrayDR = dt.Select();

            //foreach (DataRow CaseTreeNodeRode in arrayDR)
            //{
            //    TreeNode node = new TreeNode();

            //    node.Text = CaseTreeNodeRode["name"].ToString() + "(" + CaseTreeNodeRode["id"].ToString() + ")";
            //    node.Tag = CaseTreeNodeRode["id"];

            //    switch (Tname)
            //    {
            //        case "t_Case_HeadWords":
            //            if (trbll.GetTreeHeadWords(node.Tag.ToString(), Tname).Rows.Count > 0)//第二层
            //            {
            //                node.Nodes.Add(new TreeNode());
            //            }
            //            t_Case_HeadWords.TreeView.Nodes.Add(node);
            //            break;
            //        case "t_Case_JudicialProcedure":
            //            t_Case_JudicialProcedure.TreeView.Nodes.Add(node);
            //            break;
            //        case "t_Case_ParagraphType":
            //            t_Case_ParagraphType.TreeView.Nodes.Add(node);
            //            break;

            //        case "t_Global_Court":
            //            if (trbll.GetTreeHeadWords(node.Tag.ToString(), Tname).Rows.Count > 0)//第二层
            //            {
            //                node.Nodes.Add(new TreeNode());
            //            }
            //            t_Global_Court.TreeView.Nodes.Add(node);
            //            break;

            //        case "t_Case_Property":
            //            t_Case_Property.TreeView.Nodes.Add(node);
            //            break;

            //    }



            //}
        }
        public void GetTreeHeadWordsChild(TreeNode parentNode, string Tname)
        {
            DataTable dt = trbll.GetTreeHeadWords(parentNode.Tag.ToString(), Tname);// 第一层
            DataRow[] arrayDR = dt.Select();

            foreach (DataRow CaseTreeNodeRode in arrayDR)
            {
                TreeNode node = new TreeNode();

                node.Text = LdFormat.ObjectToString(CaseTreeNodeRode["name"]) + "(" + CaseTreeNodeRode["id"] + ")";
                node.Tag = CaseTreeNodeRode["id"];
                //判断是否有子节点
                if (trbll.GetTreeHeadWords(node.Tag.ToString(), Tname).Rows.Count > 0)//第二层
                {
                    node.Nodes.Add(new TreeNode());
                }
                parentNode.Nodes.Add(node);

            }

        }

        public void t_Case_HeadWords_AfterExpand(object sender, TreeViewEventArgs e)
        {
            e.Node.Nodes.Clear();
            GetTreeHeadWordsChild(e.Node, "t_Case_HeadWords");
        }
        public void t_Global_Court_AfterExpand(object sender, TreeViewEventArgs e)
        {
            e.Node.Nodes.Clear();
            GetTreeHeadWordsChild(e.Node, "t_Global_Court");
        }
        #endregion

        #region 刑事民事行政按钮(显示不同树)
        //public void GetColor()
        //{
        //    //button8.BackColor = Color.White;
        //    //button6.BackColor = Color.White;
        //    //button5.BackColor = Color.White;
        //    //button4.BackColor = Color.White;
        //    //button7.BackColor = Color.White;
        //}
        private void button8_Click(object sender, EventArgs e)
        {

        }

        private void button6_Click(object sender, EventArgs e)
        {
            TypeName = "民事案由";
            //GetColor();
            Button sendButton = (Button)sender;
            sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            TypeName = "行政案由";
            // GetColor();
            Button sendButton = (Button)sender;
            sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            TypeName = "赔偿案由";
            // GetColor();
            Button sendButton = (Button)sender;
            sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            TypeName = "执行案由";
            // GetColor();
            Button sendButton = (Button)sender;
            sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }

        #endregion

        #region 各种排序(字长、数目)

        private void SelectAdd_Click(object sender, EventArgs e)
        {
            if (txt_SelectWord.Text.Trim() != "")
                SelectText = WhereLike.ToWherelike(txt_SelectWord.Text.Trim(), "EW_Content", 1);
            else
                SelectText = "";

            dataPagerMain.ChangePageNumber(1);
        }

        private void SelectCut_Click(object sender, EventArgs e)
        {
            if (txt_SelectWord.Text.Trim() != "")
                SelectText = WhereLike.ToWherelike(txt_SelectWord.Text.Trim(), "EW_Content", 0);
            else
                SelectText = "";
            dataPagerMain.ChangePageNumber(1);
        }


        private void WordLengSort_Click(object sender, EventArgs e)
        {
            sort = "WordLengSort";
            if (IsASC == "")
            {
                IsASC = "desc";
            }
            else
            {
                IsASC = "";
            }
            dataPagerMain.ChangePageNumber(1);
        }

        private void AlphabetSort_Click(object sender, EventArgs e)
        {
            sort = "AlphabetSort";
            if (IsASC == "")
            {
                IsASC = "desc";
            }
            else
            {
                IsASC = "";
            }
            dataPagerMain.ChangePageNumber(1);
        }

        private void CountSort_Click(object sender, EventArgs e)
        {
            sort = "CountSort";
            if (IsASC == "")
            {
                IsASC = "desc";
            }
            else
            {
                IsASC = "";
            }
            dataPagerMain.ChangePageNumber(1);
        }

        private void ISCheckSort_Click(object sender, EventArgs e)
        {
            sort = "RightSort";
            if (IsASC == "")
            {
                IsASC = "desc";
            }
            else
            {
                IsASC = "";
            }
            dataPagerMain.ChangePageNumber(1);


        }

        private void NotCheckSort_Click(object sender, EventArgs e)
        {

        }
        private void IsMatch_Click(object sender, EventArgs e)
        {
            dataPagerMain.ChangePageNumber(1);
            SelectText = "";
            SelectWBK_ID = "";
            if (tabControl1.SelectedIndex == 1)
            {
                ToAddWordBanks();
            }
        }

        private void NotMatch_Click(object sender, EventArgs e)
        {
            dataPagerMain.ChangePageNumber(1);
            SelectText = "";
            SelectWBK_ID = "";
            if (tabControl1.SelectedIndex == 1)
            {
                ToAddWordBanks();
            }
        }

        private void IsAffirmIdeaResult_Click(object sender, EventArgs e)
        {
            dataPagerMain.ChangePageNumber(1);
            SelectText = "";
            SelectWBK_ID = "";
            if (tabControl1.SelectedIndex == 1)
            {
                ToAddWordBanks();
            }
        }

        private void NotAffirmIdeaResult_Click(object sender, EventArgs e)
        {
            dataPagerMain.ChangePageNumber(1);
            if (tabControl1.SelectedIndex == 1)
            {
                ToAddWordBanks();
            }
        }



        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            AddWordBank();
        }

        private void button9_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows[GridViewRowNumber].Cells["EW_ID"] != null)
            {
                AddWordBank();
                EW_IDText = dataGridView1.Rows[GridViewRowNumber].Cells["EW_ID"].Value.ToString();
                textBox1.Text = "";
                textBox1.Text = dataGridView1.Rows[GridViewRowNumber].Cells["EW_Content"].Value.ToString();
                ColorWord();
            }
        }

        private void AddWordBank()
        {
            try
            {
                SYS_WordBank_KeyWords model = new SYS_WordBank_KeyWords();
                string addelement = textBox1.SelectedText;
                string[] wordsTextArr = addelement.Split(',', '，', ';', '；');
                foreach (var item in wordsTextArr)
                {
                    if (item != "")
                    {
                        DataTable dt = wordbankbll.GetWB_IDByHeadword(clicknode.Tag.ToString());
                        if (dt.Rows.Count > 0)
                            model.WB_ID = dt.Rows[0]["WB_ID"].ToString();
                        else
                            model.WB_ID = clicknode.Tag.ToString();
                        model.WBK_Word = item;
                        model.WBK_Length = item.Length;
                        wordbankkeywordsbll.Add(model);
                    }
                }


                MsgBox.OK("添加词库成功！");
            }
            catch (Exception error)
            {
                MsgBox.Err("添加词库失败！");
                Log.ErrorLog(error.Message);

            }

        }

        /// <summary>
        /// 标红词库
        /// </summary>
        private void ColorWord()
        {
            #region 标红词库
            //textBox1.SelectionBackColor = Color.White;

            //string EW_ID = dataGridView1.Rows[GridViewRowNumber].Cells["EW_ID"].Value.ToString();
            ////string MS_ID = dataGridView1.Rows[GridViewRowNumber].Cells["MS_ID"].Value.ToString();
            //IsContentOrAddElement = 1;

            //DataTable dt = express_wordbankrelbll.Get_Express_WordBankRel(EW_ID);

            //for (int i = 0; i < dt.Rows.Count; i++)
            //{
            //    StateWord(dt.Rows[i]["WBK_Word"].ToString());

            //}

            #endregion
        }

        private void StateWord(string SelectWord)
        {

            textBox1.SelectionStart = 0;
            textBox1.SelectionLength = textBox1.Text.Length;

            System.Text.RegularExpressions.MatchCollection mc;
            System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(SelectWord); //定义一个Regex对象实例
            mc = r.Matches(textBox1.Text);
            for (int i = 0; i < mc.Count; i++) //在输入字符串中找到所有匹配
            {
                int start = mc[i].Index; //记录匹配字符的位置
                int length = (SelectWord).Length;
                textBox1.SelectionStart = start;
                textBox1.SelectionLength = length;
              //  textBox1.SelectionBackColor = Color.Red;
            }
        }
        #endregion

        #region 添加表述
        /// <summary>
        /// 添加表述
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddExpressWprd_Click(object sender, EventArgs e)
        {
            try
            {
                string ccId = clicknode.Tag.ToString();
                string caseid = "1000000";
                string ParagraphID = "150";
                string resultText = textBox1.Text;
                if (casecausebLL.GetSYS_CaseCauseByCCID(ccId).Rows.Count > 0)//单一节点
                {
                    DataTable processNodedt = work.BelongCaseCauseId(ccId);//节点匹配数据开始处
                    if (processNodedt.Rows.Count > 0)
                    {
                        work.AddToExpress(resultText, caseid, ParagraphID, processNodedt.Rows[0]["CC_ID"].ToString(), ccId);
                    }
                    else
                    {
                        MsgBox.Warn("添加失败,未找到符合条件的根节点");
                        return;
                    }
                }
                else//组合节点
                {
                    #region 添加文本
                    SYS_Express_Word WordModel = new SYS_Express_Word();
                    WordModel.MS_ID = ccId;
                    WordModel.EW_CaseId = caseid;
                    WordModel.EW_Content = resultText;
                    WordModel.EW_UseCount = 1;
                    WordModel.EW_WordCount = resultText.Length;
                    WordModel.ParagraphTypeId = Convert.ToInt32(ParagraphID);
                    WordModel.EW_ID = wordbll.Exists_WordProcess(WordModel);
                    if (WordModel.EW_ID == "")
                    {
                        WordModel.EW_ID = newid.JudgeDoc_CreateID("SYS_Express_Word");
                        WordModel.EW_Right = 0;
                        WordModel.EW_Wrong = 0;
                        wordbll.AddWord_Process(WordModel);
                    }
                    else
                    {
                        wordbll.UpdateWord_Process(WordModel);
                    }
                    #endregion

                    #region 词库
                    List<string> EW_AddElementStr = express_wordbankrelbll.WordBank("", WordModel.EW_Content);
                    foreach (var item in EW_AddElementStr)
                    {
                        if (!express_wordbankrelbll.Exists(WordModel.EW_ID, item))
                        {
                            express_wordbankrelbll.Add_Express_WordBankRel(newid.JudgeDoc_CreateID("SYS_Express_WordBankRel"), WordModel.EW_ID, item);
                        }
                    }
                    #endregion
                }
                dataPagerMain.ChangePageNumber(dataPagerMain._currentPageNumber);
                textBox1.Text = "";
                MessageBox.Show("添加表述成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show("添加表述失败！");
                Log.ErrorLog(ex.ToString());
            }
        }
        #endregion



        private void button10_Click(object sender, EventArgs e)
        {
            OpenNodeTree();
        }

        private void OpenNodeTree()
        {
            if (clicknode != null)
            {
                //ConditionExtract.NodeTree nt1 = ConditionExtract.NodeTree.Instance;
                //nt1.Close();
                ConditionExtract.NodeTree nt =new ConditionExtract.NodeTree();
                ConditionExtract.NodeTree.TypeName = TypeName;
                nt.FirId = FirId;
                nt.LocateNode = expresitu.GetES_SituationIdsById(clicknode.Tag.ToString());
                if (nt.LocateNode.Contains(","))
                {
                    nt.LocateNode = nt.LocateNode.Substring(0, nt.LocateNode.IndexOf(","));
                }
            ((MainForm)this.Parent.Parent).ShowForm(nt);
            }
        }

        private void button11_Click(object sender, EventArgs e)
        {
            ToAddWordBanks();
        }
        private TreeNode editnode = null;//点击获得当前节点
        private void tVCaseCause_MouseDown(object sender, MouseEventArgs e)
        {
            if (editnode == null) return;
            Point ClickPoint = new Point(e.X, e.Y);
            editnode = tVCaseCause.GetNodeAt(ClickPoint);
            caseModel = casecausebLL.GetCaseCauseByCCID(editnode.Tag.ToString());
            if (editnode != null)//判断你点的是不是一个节点
            {
                editnode.ContextMenuStrip = contextMenuStrip1;
                //如果是案由节点，则显示表述关系提取按钮
                if (caseModel.CC_NodeType == 2 && casecausebLL.IsLastAnYou(caseModel.CC_ID))
                {
                    if (workThread1 != null && workThread1.IsAlive)
                    {
                        biaoShuRelation.Enabled = false;
                    }
                    else
                    {
                        // biaoShuRelation.Visible = true;
                        biaoShuRelation.Enabled = true;
                    }
                }
                else
                {
                    biaoShuRelation.Enabled = false;
                    // biaoShuRelation.Visible = false;
                }
            }
        }
        private void 添加要素ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ToAddWordBanks();
        }
        private void AddNodeMenuItem_Click(object sender, EventArgs e)
        {
            group_add.Visible = true;

        }


        private void btn_quit_Click(object sender, EventArgs e)
        {
            group_add.Visible = false;
            TxtCC_ID.Text = "";
            IsMatch2.Checked = true;
            IsAffirmIdeaResult2.Checked = true;
            MatchSource.Text = "0";
            AffirmIdeaSource.Text = "0";
        }

        /// <summary>
        /// 添加节点（只能在组合下添加）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_add_Click(object sender, EventArgs e)
        {
            var newModel = new SYS_Express_MatchSituation();
            string ccId = TxtCC_ID.Text;
            //是否构成
            newModel.IsMatch = IsMatch2.Checked ? 1 : 0;
            //要素来源
            newModel.MatchSource = MatchSource.Text;
            //认定结果
            newModel.AffirmIdeaResult = IsAffirmIdeaResult2.Checked ? "1" : "2";
            //认定意见来源
            newModel.AffirmIdeaSource = AffirmIdeaSource.Text;

            string MS_ID = dataprocess_editnode.AddNode(ccId, editnode.Tag.ToString(), newModel);
            //添加完以后界面显示
            if (MS_ID != "")
            {
                MessageBox.Show("添加成功！");
                newModel = express_matchsituationbll.GetMatchSituation(MS_ID);
                clicknode.Expand();
                TreeNode addnode = new TreeNode();
                addnode.Tag = newModel.MS_ID;
                addnode.Text = newModel.SituationName;
                addnode.Name = newModel.SituationType.ToString();
                clicknode.Nodes.Add(addnode);
            }
            else
            {
                MessageBox.Show("添加失败，节点只能在组合部分添加！");
            }
            group_add.Visible = false;
        }


        #region 情形情节树(条件)

        /// <summary>
        /// 树（第一级）
        /// </summary>
        //public void CaseCauseTree_Process()
        //{
        //    DataTable dt = trbll.NodeTree_Tree("");
        //    DataRow[] arrayDR = dt.Select("name='" + "刑事罪名" + "'");

        //    foreach (DataRow caseTreeNodeRode in arrayDR)
        //    {
        //        var node = new TreeNode
        //        {
        //            Text =
        //                LdFormat.ObjectToString(caseTreeNodeRode[1]) + "(" +
        //                LdFormat.ObjectToString(caseTreeNodeRode[0]) + ")",
        //            Tag = caseTreeNodeRode[0],
        //            Name = LdFormat.ObjectToString(caseTreeNodeRode[2])
        //        };

        //        FirId = caseTreeNodeRode[0].ToString();
        //        if (trbll.NodeTree_Tree(node.Tag.ToString()).Rows.Count > 0)
        //        {
        //            node.Nodes.Add(new TreeNode());
        //        }
        //        NowProcessNode.TreeView.Nodes.Add(node);
        //    }
        //}
        /// <summary>
        /// 下级树
        /// </summary>
        /// <param name="parentNode"></param>
        private void CaseCauseTreeChild_Process(TreeNode parentNode)
        {
            string pid = parentNode.Tag.ToString();
            DataTable caseTreeNodeRode = trbll.NodeTree_Tree(pid);
            if (caseTreeNodeRode.Rows.Count == 0)
                return;
            for (int i = 0; i < caseTreeNodeRode.Rows.Count; i++)
            {
                var node = new TreeNode
                {
                    Text = caseTreeNodeRode.Rows[i]["name"] + @"(" + caseTreeNodeRode.Rows[i]["id"] + @")",
                    Tag = caseTreeNodeRode.Rows[i]["id"],
                    Name = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["CC_NodeType"])
                };


                if (trbll.NodeTree_Tree(node.Tag.ToString()).Rows.Count > 0)
                {
                    node.Nodes.Add(new TreeNode());
                }
                parentNode.Nodes.Add(node);
            }
        }

        private void NowProcessNode_AfterExpand(object sender, TreeViewEventArgs e)
        {
            e.Node.Nodes.Clear();
            CaseCauseTreeChild_Process(e.Node);
        }

        #endregion

        private void GV_Reg_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                OpenNodeTree();
            }
        }


        private void AgainOrganTree_Click(object sender, EventArgs e)
        {
            if (workThread == null)//创建线程
            {
                #region 查询条件

                DataSourceCondition condi = new DataSourceCondition(); //条件
                #endregion

                workObj = WorkThreadFactory.CreateWorkThreadObj("WorkThread_Order");
                ThreadExecute(condi, null);

            }

        }

        private void groupBox2_Enter(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 全部展开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 全部展开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AllExpandNode(editnode.Tag.ToString());//展开全部
        }

        /// <summary>
        /// 展开全部
        /// </summary>
        /// <param name="pid"></param>
        private void AllExpandNode(string pid)
        {

            var findNode = FindNode(pid);
            if (findNode != null) findNode.ExpandAll();

            //DataTable caseTreeNodeRode = trbll.NodeTree_Tree(pid);//父级ID的下级节点
            //if (caseTreeNodeRode.Rows.Count == 0)
            //    return;
            //for (int i = 0; i < caseTreeNodeRode.Rows.Count; i++)
            //{
            //    TreeNode node = new TreeNode();
            //    node.Text = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["name"]);
            //    node.Tag = caseTreeNodeRode.Rows[i]["id"];
            //    node.Name = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["CC_NodeType"]);
            //    AllExpandNode(node.Tag.ToString());
            //}
        }

        //private void button4_Click_1(object sender, EventArgs e)
        //{
        //    SYS_CaseCause objCaseCause = casecausebLL.GetCaseCauseByCCID(NowProcessNode.Text.Trim());
        //    if (objCaseCause != null && !string.IsNullOrEmpty(objCaseCause.CC_Name))
        //    {
        //        if (MsgBox.Ask("是否删除" + objCaseCause.CC_Name + "(" + NowProcessNode.Text + ")" + "下的表述节点及其表述内容？") == DialogResult.Yes)
        //        {
        //            //express_matchsituationbll.DeleteSYS_Express_MatchSituation(NowProcessNode.Text.Trim());
        //            if (wordbll.DeleteSYS_Express_Word_Process(NowProcessNode.Text.Trim()) && express_matchsituationbll.DeleteSYS_Express_MatchSituation(NowProcessNode.Text.Trim()))
        //            {
        //                MessageBox.Show("删除成功！");
        //            }
        //            else
        //            {
        //                MessageBox.Show("删除失败！");
        //            }
        //        }
        //    }
        //    else
        //    {
        //        MessageBox.Show("请先选择处理节点！");
        //    }
        //}

        //表述关系提取
        private void biaoShuRelation_Click(object sender, EventArgs e)
        {
            if (workThread1 != null && workThread1.IsAlive)
            {
                biaoShuRelation.Enabled = false;
                processBar.Visible = progressBar1.Visible = false;
            }
            else
            {
                processBar.Visible = progressBar1.Visible = true;
                workThread1 = new Thread(Execute_Start);
                workThread1.Start();
            }            
        }

        public void ShowProgress(string str)
        {
            if (processBar.InvokeRequired)
            {
                // 当一个控件的InvokeRequired属性值为真时，说明有一个创建它以外的线程想访问它
                Action<string> actionDelegate = (x) => { this.processBar.Text = x.ToString(); };
                // 或者
                // Action<string> actionDelegate = delegate(string txt) { this.label2.Text = txt; };
                this.processBar.Invoke(actionDelegate, str);
            }
        }

        //表述关系生成
        public void Execute_Start()
        {
            try
            {
                if(NowProcessNode.Text.Trim() == "")
                {
                    MessageBox.Show("请输入处理节点！");
                    return;
                }
                m_causecode = casecausebLL.GetCriminalNodes(NowProcessNode.Text.Trim());
                if(m_causecode.Rows.Count == 0)
                {
                    MessageBox.Show("输入的不是一个有效节点！");
                    return;
                }
                ShowProgress("正在生成单节点表述，请稍后......");
                m_single = CaseCauseCondBLL.getSingleNodes(NowProcessNode.Text.Trim());
                ShowProgress("单节点表述生成完毕");
                ShowProgress("正在生成组合节点表述,请稍后......");
                AddMatchSituation(m_causecode, NowProcessNode.Text.Trim());
                ShowProgress("组合节点表述生成完毕");
                // processBar.Visible = progressBar1.Visible = false;

                if (m_group != null && m_group.Rows.Count > 0)
                {
                    DataView dv = m_group.DefaultView;
                    dv.Sort = "allparentid asc";
                    m_group = dv.ToTable();
                }

                if (m_matchsituation != null && m_matchsituation.Rows.Count > 0)
                {
                    DataView dv1 = m_matchsituation.DefaultView;
                    dv1.Sort = "AllParenId asc";
                    m_matchsituation = dv1.ToTable();
                }
                string a = "";
                for (int i = m_matchsituation.Rows.Count - 1; i >= 0; i--)
                {
                    string allParentId = m_matchsituation.Rows[i]["AllParenId"].ToString();
                    if (a == allParentId)
                        m_matchsituation.Rows.RemoveAt(i);
                    else a = allParentId;
                }
                ShowProgress("全部生成完毕");
                ShowProgress("保存数据到表述关系表");
                //保存数据到数据库
                //1.添加到SYS_Express_MatchSituation表
                string st = "";
                for (int i = 0; i < m_matchsituation.Rows.Count; i++)
                {

                    ShowProgress(string.Format("{0}/{1}", i + 1, m_matchsituation.Rows.Count));
                    SYS_Express_MatchSituation stiuModel = new SYS_Express_MatchSituation();
                    stiuModel.IsMatch = Convert.ToInt32(m_matchsituation.Rows[i]["IsMatch"] == null ? "0" : m_matchsituation.Rows[i]["IsMatch"]);
                    stiuModel.MatchSource = m_matchsituation.Rows[i]["MatchSource"] == null ? "0" : m_matchsituation.Rows[i]["MatchSource"].ToString();
                    stiuModel.AffirmIdeaResult = m_matchsituation.Rows[i]["AffirmIdeaResult"].ToString();
                    stiuModel.AffirmIdeaSource = m_matchsituation.Rows[i]["AffirmIdeaSource"].ToString();
                    stiuModel.SituationID = m_matchsituation.Rows[i]["CauseId"].ToString();
                    stiuModel.AllStituationIDs = m_matchsituation.Rows[i]["AllStituationIDs"].ToString();
                    string msId = MatchSituationbll.Exists_MatchSituation(stiuModel.SituationID, stiuModel.IsMatch, stiuModel.MatchSource, stiuModel.AffirmIdeaResult, stiuModel.AffirmIdeaSource, stiuModel.AllStituationIDs, m_matchsituation.Rows[i]["ParentID"] == null ? "" : m_matchsituation.Rows[i]["ParentID"].ToString(),"");//存在
                    if (msId == "")
                    {
                        stiuModel.MS_ID = m_matchsituation.Rows[i]["MS_ID"].ToString();
                        stiuModel.CauseGroupID= m_matchsituation.Rows[i]["CauseGroupID"].ToString();
                        stiuModel.SituationType =Convert.ToInt32(m_matchsituation.Rows[i]["CcNodeType"].ToString());
                        stiuModel.SituationName= m_matchsituation.Rows[i]["CauseName"].ToString();
                        stiuModel.AllParentID = m_matchsituation.Rows[i]["AllParentID"] == null ? "" : m_matchsituation.Rows[i]["AllParentID"].ToString();               
                        stiuModel.ParentID = m_matchsituation.Rows[i]["ParentID"] == null ? "" : m_matchsituation.Rows[i]["ParentID"].ToString();
                        stiuModel.CC_IsShowExpress = 0;

                        MatchSituationbll.AddMatchSituation(stiuModel);//添加
                    }
                }
                //添加到SYS_Express_Word_Process表
                ShowProgress("保存数据到表述表");
                //                foreach (DataRow dr in m_single.Rows)
                for (int i = 0; i < m_single.Rows.Count; i++)
                {
                    ShowProgress(string.Format("{0}/{1}", i + 1, m_single.Rows.Count));
                    string msid = "";
                    SYS_Express_Word wordModel = new SYS_Express_Word();
                    DataRow[] dr1 = m_matchsituation.Select("CauseId='" + m_single.Rows[i]["CauseId"].ToString() + "'");
                    for (int j = 0; j < dr1.Length; j++)
                    {
                        if (dr1.Length > 1)
                        {
                            if (dr1[j]["ParenId"].ToString().Contains("S"))
                            {
                                msid = m_matchsituation.Select("ParenId='" + dr1[j]["ParenId"].ToString() + "'")[0]["MS_ID"].ToString();
                            }
                        }
                        else
                        {
                            msid = m_matchsituation.Select("ParenId='" + dr1[j]["ParenId"].ToString() + "'")[0]["MS_ID"].ToString();
                        }
                    }
                    wordModel.MS_ID = msid;


                    wordModel.EW_CaseId = m_single.Rows[i]["CaseId"].ToString();
                    wordModel.EW_Content = m_single.Rows[i]["CC_Formatting"].ToString();

                    wordModel.EW_UseCount = 1;
                    wordModel.EW_WordCount = m_single.Rows[i]["CC_Formatting"].ToString().Length;
                    wordModel.ParagraphTypeId = 150;

                    wordModel.EW_ID = wordbll.Exists_WordProcess(wordModel);
                    wordModel.EW_IsSingleExpress = 0;
                    if (wordModel.EW_ID == "")
                    {
                        wordModel.EW_ID = newid.JudgeDoc_CreateID("SYS_Express_Word");
                        wordModel.EW_Right = 0;
                        wordModel.EW_Wrong = 0;

                        wordbll.AddWord_Process(wordModel);
                    }
                    else
                    {
                        wordbll.UpdateWord_Process(wordModel);
                    }
                }

                ShowProgress("全部生成完毕1");

                // foreach (DataRow dr in m_group.Rows)
                for (int i = 0; i < m_group.Rows.Count; i++)
                {
                    ShowProgress(string.Format("{0}/{1}", i + 1, m_group.Rows.Count));
                    string msid = "";
                    SYS_Express_Word wordModel = new SYS_Express_Word();
                    DataRow[] dr1 = m_matchsituation.Select("CauseId='" + m_group.Rows[i]["CauseId"].ToString() + "'");
                    for (int j = 0; j < dr1.Length; j++)
                    {
                        if (dr1.Length > 1)
                        {
                            if (dr1[j]["ParenId"].ToString().Contains("G"))
                            {
                                msid = m_matchsituation.Select("ParenId='" + dr1[j]["ParenId"].ToString() + "'")[0]["MS_ID"].ToString();
                            }
                        }
                        else
                        {
                            msid = m_matchsituation.Select("ParenId='" + dr1[j]["ParenId"].ToString() + "'")[0]["MS_ID"].ToString();
                        }
                    }
                    wordModel.MS_ID = msid;


                    wordModel.EW_CaseId = m_group.Rows[i]["CaseId"].ToString();
                    wordModel.EW_Content = m_group.Rows[i]["CC_Formatting"].ToString();

                    wordModel.EW_UseCount = 1;
                    wordModel.EW_WordCount = m_group.Rows[i]["CC_Formatting"].ToString().Length;
                    wordModel.ParagraphTypeId = 150;

                    wordModel.EW_ID = wordbll.Exists_WordProcess(wordModel);
                    wordModel.EW_IsSingleExpress = 1;
                    if (wordModel.EW_ID == "")
                    {
                        wordModel.EW_ID = newid.JudgeDoc_CreateID("SYS_Express_Word");
                        wordModel.EW_Right = 0;
                        wordModel.EW_Wrong = 0;

                        wordbll.AddWord_Process(wordModel);
                    }
                    else
                    {
                        wordbll.UpdateWord_Process(wordModel);
                    }
                }
                ShowProgress("全部生成完毕2");
            }
            catch (Exception ex)
            {
                throw;
            }
        }


        /// <summary>
        /// 添加表述
        /// </summary>
        /// <param name="CaseCauseID">案由小分类ID</param>
        /// <param name="ParagraphID">逻辑段140，150</param>
        /// <param name="resultText">索引句子</param>
        /// <param name="CC_IDList">ID字符串</param>
        /// <param name="caseid">案例ID</param>
        public void AddToExpress(string resultText, string caseid, string ParagraphID, string CaseCauseID, string CC_IDList)
        {
            #region 添加match表

            #region 节点属性
            bool ismatchb = getregex.IsMatch("3F53BB8A-08CC-4F55-89A9-8EAAE4FC3163", resultText);//true 不构成
            int ismatch = ismatchb ? 0 : 1;
            bool affirmIdeaResultb = getregex.IsMatch("EI1601201151020001", resultText);//true 不认定
            string affirmIdeaResult = affirmIdeaResultb ? "2" : "1";
            var stiuModel = new SYS_Express_MatchSituation
            {
                IsMatch = ismatch,
                MatchSource = "0",
                AffirmIdeaResult = affirmIdeaResult,
                AffirmIdeaSource = "0"
            };

            #endregion

            string msId = "";

            //组合情形
            string[] situationIDa = CC_IDList.Split(',');
            //2017-07-13 ljj 修改
            if (situationIDa.Length == 1)
            {
                msId = work.AddSingleMatch(situationIDa[0], CaseCauseID, situationIDa[0], CaseCauseID, stiuModel, "-1", true);//从0开始
            }
            else if (situationIDa.Length > 1)
            {
                string allCombinePid = situationIDa[0];
                string allMsIdPid = "";

                msId = work.AddMatch(situationIDa[0], CaseCauseID, allCombinePid, CaseCauseID, stiuModel, allMsIdPid, true);//从0开始
                for (int i = 1; i < situationIDa.Length; i++)
                {
                    allCombinePid = allCombinePid + "," + situationIDa[i];
                    if (allMsIdPid != "")
                        allMsIdPid += "," + msId;
                    else
                        allMsIdPid += msId;

                    msId = work.AddMatch(situationIDa[i], msId, allCombinePid, CaseCauseID, stiuModel, allMsIdPid, true);
                }
            }
            #endregion

            #region 添加文本

            SYS_Express_Word wordModel = new SYS_Express_Word();
            wordModel.MS_ID = msId;


            wordModel.EW_CaseId = caseid;
            wordModel.EW_Content = resultText;

            wordModel.EW_UseCount = 1;
            wordModel.EW_WordCount = resultText.Length;
            wordModel.ParagraphTypeId = Convert.ToInt32(ParagraphID);

            wordModel.EW_ID = wordbll.Exists_WordProcess(wordModel);

            if (wordModel.EW_ID == "")
            {
                wordModel.EW_ID = newid.JudgeDoc_CreateID("SYS_Express_Word");
                wordModel.EW_Right = 0;
                wordModel.EW_Wrong = 0;

                wordbll.AddWord_Process(wordModel);
            }
            else
            {
                wordbll.UpdateWord_Process(wordModel);
            }
            #endregion

            #region 词库
            var ewAddElementStr = express_wordbankrelbll.WordBank("", wordModel.EW_Content);

            foreach (var item in ewAddElementStr)
            {
                if (!express_wordbankrelbll.Exists(wordModel.EW_ID, item))
                {

                    express_wordbankrelbll.Add_Express_WordBankRel(newid.JudgeDoc_CreateID("SYS_Express_WordBankRel"), wordModel.EW_ID, item);
                }
            }
            #endregion
        }


        /// <summary>
        /// 生成表述关系上层节点
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="ccId"></param>
        private void AddMatchSituation(DataTable casecasuseNodes, string ccId)
        {
            try
            {
                //该节点的下一级节点
                DataRow[] dr = casecasuseNodes.Select(" CC_ParentID='" + ccId + "'", "CC_GlobalOrder asc");
                for (int i = 0; i < dr.Length; i++)
                {
                    //CcNodeType
                    //构造该节点下单一组合树
                    DataRow dr1 = m_matchsituation.NewRow();
                    dr1["MS_ID"] = newid.JudgeDoc_CreateID("SYS_Express_MatchSituation");
                    dr1["CauseGroupID"] = dr[i]["CC_ID"];
                    dr1["SituationID"] = dr[i]["CC_ID"];
                    dr1["SituationType"] = dr[i]["CC_NodeType"];
                    dr1["SituationName"] = dr[i]["CC_Name"];
                    dr1["IsMatch"] = "0";
                    dr1["MatchSource"] = "0";
                    dr1["AffirmIdeaSource"] = "0";
                    dr1["AffirmIdeaResult"] = "0";
                    dr1["notAffirmReson"] = "0";
                    dr1["ParentID"] = ccId;
                    dr1["AllSituationIDs"] = dr1["MS_ID"];
                    dr1["AllParentID"] = dr[i]["CC_ID"];
                    dr1["CC_IsShowExpress"] = "0";
                    dr1["UpdateTime"] = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                    dr1["CC_GlobalOrder"] = dr[i]["CC_GlobalOrder"];
                    m_matchsituation.Rows.Add(dr1);

                    DataRow dr2 = m_matchsituation.NewRow();
                    dr2["MS_ID"] = "M" + dr[i]["CC_ID"];
                    dr2["CauseGroupID"] = dr[i]["CC_ID"];
                    dr2["SituationID"] = "M" + dr[i]["CC_ID"];
                    dr2["SituationType"] = "9";
                    dr2["SituationName"] = "组合";
                    dr2["IsMatch"] = "0";
                    dr2["MatchSource"] = "0";
                    dr2["AffirmIdeaSource"] = "0";
                    dr2["AffirmIdeaResult"] = "0";
                    dr2["notAffirmReson"] = "0";
                    dr2["ParentID"] = dr[i]["CC_ID"];
                    dr2["AllSituationIDs"] = dr2["MS_ID"];
                    dr2["AllParentID"] = dr[i]["CC_ID"] + ",M";
                    dr2["CC_IsShowExpress"] = "0";
                    dr2["UpdateTime"] = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                    dr2["CC_GlobalOrder"] = dr[i]["CC_GlobalOrder"] + "0";

                    m_matchsituation.Rows.Add(dr2);

                    DataRow dr3 = m_matchsituation.NewRow();
                    dr3["MS_ID"] = "S" + dr[i]["CC_ID"];
                    dr3["CauseGroupID"] = dr[i]["CC_ID"];
                    dr3["SituationID"] = "S" + dr[i]["CC_ID"];
                    dr3["SituationType"] = "9";
                    dr3["SituationName"] = "单一";
                    dr3["IsMatch"] = "0";
                    dr3["MatchSource"] = "0";
                    dr3["AffirmIdeaSource"] = "0";
                    dr3["AffirmIdeaResult"] = "0";
                    dr3["notAffirmReson"] = "0";
                    dr3["ParentID"] = dr[i]["CC_ID"];
                    dr3["AllSituationIDs"] = dr3["MS_ID"];
                    dr3["AllParentID"] = dr[i]["CC_ID"] + ",S";
                    dr3["CC_IsShowExpress"] = "0";
                    dr3["UpdateTime"] = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                    dr3["CC_GlobalOrder"] = dr[i]["CC_GlobalOrder"] + "00";
                    m_matchsituation.Rows.Add(dr3);

                    groupStr = dr2["AllParentID"].ToString();
                    singleStr = dr3["AllParentID"].ToString();
                    AddSingleMatchSituation(casecasuseNodes, dr1["SituationID"].ToString(), dr3["AllSituationIDs"].ToString(), dr3["AllParentID"].ToString(), dr3["MS_ID"].ToString());
                    GetGroupExpress(dr1["CauseId"].ToString(), dr2["AllParenId"].ToString(), dr2["MS_ID"].ToString(), dr2["AllParentID"].ToString());

                }
            }
            catch (Exception ex)
            {

                throw;
            }
        }

        /// <summary>
        /// 生成单一表述关系节点树
        /// </summary>
        /// <param name="casecasuseNodes"></param>
        /// <param name="ccId"></param>
        /// <param name="parentId"></param>
        private void AddSingleMatchSituation(DataTable casecasuseNodes, string ccId, string allSituatonIDs, string parentID, string msId)
        {
            try
            {
                //递归加载单一节点树下面的节点
                DataRow[] dr = casecasuseNodes.Select("CC_ParentID='" + ccId + "'", "CC_GlobalOrder");
                for (int i = 0; i < dr.Length; i++)
                {
                    DataRow dr1 = m_matchsituation.NewRow();
                    dr1["MS_ID"] = newid.JudgeDoc_CreateID("SYS_Express_MatchSituation");
                    dr1["CauseGroupID"] = dr[i]["CC_ID"];
                    dr1["SituationID"] = dr[i]["CC_ID"];
                    dr1["SituationType"] = dr[i]["CC_NodeType"];
                    dr1["SituationName"] = dr[i]["CC_Name"];
                    dr1["IsMatch"] = "1";
                    dr1["MatchSource"] = "0";
                    dr1["AffirmIdeaSource"] = "0";
                    dr1["AffirmIdeaResult"] = "1";
                    dr1["notAffirmReson"] = "0";
                    dr1["ParentID"] = msId;
                    dr1["AllSituationIDs"] = allSituatonIDs + "," + dr1["MS_ID"];
                    dr1["AllParentID"] = parentID + "," + dr[i]["CC_ID"];
                    dr1["CC_IsShowExpress"] = "0";
                    dr1["UpdateTime"] = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                    dr1["CC_GlobalOrder"] = dr[i]["CC_GlobalOrder"];

                    m_matchsituation.Rows.Add(dr1);
                    AddSingleMatchSituation(casecasuseNodes, dr1["SituationID"].ToString(), dr1["AllSituationIDs"].ToString(), dr1["AllParentID"].ToString(), dr1["MS_ID"].ToString());

                }
            }
            catch (Exception ex)
            {

                throw;
            }
        }

        /// <summary>
        ///生成组合树 
        /// </summary>
        /// <param name="causeId"></param>
        /// <param name="parentId"></param>
        private void GetGroupExpress(string ccId, string parentId, string msID, string allParentID)
        {
            try
            {
                if (m_group.Rows.Count == 0)
                {
                    m_group = m_single.Clone();
                }
                //获取组合节点数据
                DataTable groupData = CaseCauseCondBLL.getGroupNodes(ccId);
                DataTable dt = new DataTable();
                string crccode = "";
                for (int i = 0; i < groupData.Rows.Count; i++)
                {
                    ShowProgress(string.Format("{0}/{1}", i + 1, groupData.Rows.Count));
                    DataRow dr = groupData.Rows[i];
                    dr["CC_GlobalOrder"] = m_causecode.Select("CC_ID='" + dr["CauseId"].ToString() + "'")[0]["CC_GlobalOrder"].ToString();
                    string _crccode = dr["CC_TextCRCCode"].ToString();
                    if (crccode == _crccode)
                    {

                        //相同CC_TextCRCCode的分到一组
                        dt.ImportRow(dr);
                        if (i == groupData.Rows.Count - 1)
                        {
                            AddGroupMatchSituation(groupData, dt, parentId, msID, allParentID);
                        }
                    }
                    else
                    {
                        if (i != 0)
                        {
                            AddGroupMatchSituation(groupData, dt, parentId, msID, allParentID);
                        }
                        crccode = _crccode;
                        dt = new DataTable();
                        dt = groupData.Clone();
                        dt.ImportRow(dr);
                    }
                }
            }
            catch (Exception ex)
            {

                throw;
            }



        }

        private void AddGroupMatchSituation(DataTable groupData, DataTable dt, string parentId, string msID, string allParentID)
        {
            try
            {
                DataRow[] arrdr = dt.Select("", "CC_GlobalOrder");
                DataRow dr = arrdr[0];
                string allcauseids = "";
                for (int i = 0; i < arrdr.Length; i++)
                {
                    string causeId = arrdr[i]["CauseId"].ToString();
                    //排除子节点和父节点的组合(按照业务，这个不算组合节点)
                    if (dt.Select("AllParentId like '%," + causeId + ",%'").Length == 1)
                    {
                        allcauseids += arrdr[i]["CauseId"].ToString() + ",";
                        dr["AllParentId"] = parentId + allcauseids;
                        dr["CauseId"] = causeId;
                    }
                }
                if (allcauseids.Split(',').Length <= 2)
                {
                    DataRow[] drms = m_matchsituation.Select("CauseId='" + dr["CauseId"].ToString() + "' and AllParenId like '%,S,%'");
                    dr["AllParentId"] = drms[0]["AllParentId"].ToString();
                    m_single.ImportRow(dr);
                }
                else
                {
                    m_group.ImportRow(dr);
                    AddMatchSituation(groupData, m_group, allcauseids, parentId, msID, allParentID);
                }
            }
            catch (Exception ex)
            {

                throw;
            }
        }

        private void AddMatchSituation(DataTable groupData, DataTable m_group, string caseids, string parentId, string msID, string allParentID)
        {
            try
            {
                string[] arr = caseids.Split(',');
                string allParentId = "";
                string _parentId = parentId;
                for (int i = 0; i < arr.Length - 1; i++)
                {
                    DataRow dr = m_matchsituation.NewRow();
                    dr["CauseId"] = arr[i].ToString();
                    dr["CauseName"] = m_causecode.Select("CC_ID='" + arr[i] + "'")[0]["CC_Name"].ToString();
                    allParentId += arr[i] + ",";
                    dr["MS_ID"] = newid.JudgeDoc_CreateID("SYS_Express_MatchSituation");
                    if (i == 0)
                    {
                        dr["ParenId"] = _parentId;
                        dr["ParentID"] = msID;
                        dr["AllParentID"] = allParentID + "," + dr["MS_ID"].ToString();
                    }
                    else
                    {
                        _parentId += arr[i - 1] + ",";
                        dr["ParenId"] = _parentId;
                        dr["ParentID"] = m_matchsituation.Select("AllParenId='" + dr["ParenId"] + "'")[0]["MS_ID"];
                        dr["AllParentID"] = m_matchsituation.Select("AllParenId='" + dr["ParenId"] + "'")[0]["AllParentID"] + "," + dr["MS_ID"].ToString();
                    }
                    dr["AllParenId"] = parentId + allParentId;
                    dr["SerialNumb"] = m_causecode.Select("CC_ID='" + arr[i] + "'")[0]["CC_GlobalOrder"].ToString();
                    dr["IsMatch"] = groupData.Select("CauseId='" + arr[i] + "'")[0]["CC_IsMatch"].ToString();
                    dr["AffirmIdeaResult"] = groupData.Select("CauseId='" + arr[i] + "'")[0]["CC_AffirmIdeaResult"].ToString();
                    dr["CcNodeType"] = groupData.Select("CauseId='" + arr[i] + "'")[0]["CC_NodeType"].ToString();
                    string Name = "(";
                    if (dr["IsMatch"].ToString() == "1")
                    {
                        Name += "构成";
                    }
                    else
                    {
                        Name += "不构成";
                    }
                    if (dr["AffirmIdeaResult"].ToString() == "1")
                    {
                        Name += ",认定";
                    }
                    else
                    {
                        Name += ",不认定";
                    }
                    Name += ")";
                    dr["SituationName"] = dr["CauseName"] + Name;
                    dr["MatchSource"] = "0";
                    dr["AffirmIdeaSource"] = "0";
                    dr["CauseGroupID"] = dr["AllParenId"].ToString().Split(',')[1].ToString();
                    dr["AllStituationIDs"] = dr["AllParenId"].ToString().Replace(groupStr, "").Trim();


                    m_matchsituation.Rows.Add(dr);
                }
            }
            catch (Exception ex)
            {

                throw;
            }
        }

        private void button3_Click_1(object sender, EventArgs e)
        {
            if (workThread1 != null && workThread1.IsAlive)
            {
                biaoShuRelation.Enabled = false;
                processBar.Visible = progressBar1.Visible = false;
            }
            else
            {
                processBar.Visible = progressBar1.Visible = true;
                workThread1 = new Thread(Execute_Start);
                workThread1.Start();
            }
        }

        //string NameAdd = "（";


        ////是否显示构成不构成（刑事案例用） todo by zhangpeng 2017-01-04 新需求
        //if (isDisplayMatch)
        //{
        //    if (stiuModel.IsMatch == 1)
        //    { NameAdd += "构成"; }
        //    else { NameAdd += "不构成"; }
        //    if (stiuModel.AffirmIdeaResult == "2")
        //    { NameAdd += ",不认定"; }
        //    else { NameAdd += ",认定"; }
        //}
        //else
        //{
        //    if (stiuModel.AffirmIdeaResult == "2")
        //    { NameAdd += "不认定"; }
        //    else { NameAdd += "认定"; }

        //}
        //NameAdd += "）";


        // string msId = MatchSituationbll.Exists_MatchSituation(stiuid, stiuModel.IsMatch, stiuModel.MatchSource, stiuModel.AffirmIdeaResult, stiuModel.AffirmIdeaSource, allStituationIDs);//存在
        //if (msId == "")
        //{
        //    stiuModel.MS_ID = newid.JudgeDoc_CreateID("SYS_Express_MatchSituation");
        //    msId = stiuModel.MS_ID;
        //    stiuModel.SituationID = stiuid;
        //    DataTable dtStiuid = casecausebLL.GetSYS_CaseCauseByCCID(stiuid);
        //    stiuModel.SituationType = Convert.ToInt32(dtStiuid.Rows[0]["CC_NodeType"]);
        //    stiuModel.SituationName = dtStiuid.Rows[0]["CC_Name"] + NameAdd;
        //    stiuModel.ParentID = parentId;
        //    stiuModel.AllStituationIDs = allStituationIDs;
        //    if (allParentId == "")
        //        stiuModel.AllParentID = stiuModel.MS_ID;
        //    else
        //        stiuModel.AllParentID = allParentId + "," + stiuModel.MS_ID;
        //    stiuModel.CauseGroupID = causeGroupId;
        //    stiuModel.CC_IsShowExpress = 0;

        //    MatchSituationbll.AddMatchSituation(stiuModel);//添加
        //}
        //return msId;






    }
}